package com.jvmoutofmemory.platform.pushutil.util;

import org.apache.commons.lang3.StringUtils;

/**
 * @author adam
 * @date 2021-11-17
 */
public class PushStringUtils {

    /**
     * 驼峰命名转换为数据库的下划线
     *
     * @param str
     * @return
     */
    public static String humpToUnderScore(String str) {
        if (StringUtils.isEmpty(str))
            return str;

        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        int lastLowercaseIdx = -1;
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (Character.isLowerCase(ch)) {
                lastLowercaseIdx = i;
                stringBuilder.append(ch);
            } else if (lastLowercaseIdx > 0 && lastLowercaseIdx + 1 == i) {
                stringBuilder.append("_").append(Character.toLowerCase(ch));
            } else {
                stringBuilder.append(ch);
            }
        }

        return stringBuilder.toString();
    }

}
